import * as step from '@flow-step/step-toolkit'
import * as sinon from 'sinon'
import * as path from 'path'
import {expect} from 'chai'
import * as certificate from '@flow-step/step-toolkit/src/certificate/certificate'

const proxyquire = require('proxyquire')

describe('setup', () => {
    let sandbox: sinon.SinonSandbox
    let stepExportEnvVarStub: sinon.SinonStub
    let getNpmPrivateRepoCertificateStub: sinon.SinonStub

    const fsStub = {
        dirname: sinon.stub(),
        mkdirSync: sinon.stub(),
        writeFileSync: sinon.stub()
    }
    const {setup} = proxyquire('../src/step', {
        fs: fsStub
    })

    beforeEach(() => {
        sandbox = sinon.createSandbox()
        stepExportEnvVarStub = sandbox.stub(step, 'exportEnvVar')
        getNpmPrivateRepoCertificateStub = sandbox.stub(step.certificate, 'getNpmPrivateRepoCertificate')
    })

    afterEach(() => {
        sandbox.restore()
    })

    it('should create the directory and write NPM private repo config content to the file', async () => {
        const flowJobToken = 'some-token'
        const npmPrivateRepoConfigPath = '/path/to/npm/.npmrc'
        const npmPrivateRepoCertificate: certificate.NpmCertificate = {
            npmRepoConfigContent: 'registry=http://xxx/npm/'
        }

        getNpmPrivateRepoCertificateStub.resolves(npmPrivateRepoCertificate)

        await setup(flowJobToken, npmPrivateRepoConfigPath)

        sinon.assert.calledWith(stepExportEnvVarStub, 'NPM_PRIVATE_REPO_CONFIG_PATH')
        sinon.assert.calledWith(fsStub.mkdirSync, path.dirname(npmPrivateRepoConfigPath), {recursive: true})
        sinon.assert.calledWith(fsStub.writeFileSync, npmPrivateRepoConfigPath, npmPrivateRepoCertificate.npmRepoConfigContent)
    })

    it('should throw an error if NPM private repo config content is empty', async () => {
        const flowJobToken = 'some-token'
        const npmPrivateRepoConfigPath = '/path/to/npm/.npmrc'

        getNpmPrivateRepoCertificateStub.resolves(undefined)

        try {
            await setup(flowJobToken, npmPrivateRepoConfigPath)
            expect(1).to.be.equal(0)
        } catch (error: any) {
            expect(error.message).to.be.equal('NPM private repo config content is empty')
        }
    })
})